package com.bestcem.xm.ticket.mq.send.biz.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.lang.Validator;
import cn.hutool.json.JSONUtil;
import com.bestcem.xm.common.core.config.mq.XmMessageProducer;
import com.bestcem.xm.common.core.constant.StreamMqBinderConstants;
import com.bestcem.xm.common.core.uitls.MsgPackFormatUtil;
import com.bestcem.xm.ticket.constant.Constants;
import com.bestcem.xm.ticket.dao.TicketConfigDao;
import com.bestcem.xm.ticket.dao.TicketDao;
import com.bestcem.xm.ticket.dao.TicketRecordDao;
import com.bestcem.xm.ticket.dao.dto.RspdTimerDTO;
import com.bestcem.xm.ticket.entity.mongo.Ticket;
import com.bestcem.xm.ticket.entity.mongo.TicketConfig;
import com.bestcem.xm.ticket.entity.mongo.TicketRecord;
import com.bestcem.xm.ticket.enums.MemberFootprintTypeEnum;
import com.bestcem.xm.ticket.enums.TicketOperationTypeEnum;
import com.bestcem.xm.ticket.grpc.client.TicketBaseQdesGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.qdes.QdesDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.GroupDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.GroupNodeDTO;
import com.bestcem.xm.ticket.mq.dto.FootprintMessage;
import com.bestcem.xm.ticket.mq.send.biz.TicketMessageSendService;
import com.bestcem.xm.ticket.service.dto.mq.FollowOverdueDTO;
import com.bestcem.xm.ticket.service.dto.mq.TicketSendDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Component
@Slf4j
public class TicketMessageSendServiceImpl implements TicketMessageSendService {

    @Resource
    private TicketUserGrpcService ticketUserGrpcService;

    @Resource
    private TicketBaseUserGrpcService ticketBaseUserGrpcService;

    @Resource
    private TicketBaseQdesGrpcService ticketBaseQdesGrpcService;

    @Resource
    private TicketConfigDao ticketConfigDao;

//    @Autowired
//    private RabbitMqConstantConfig rabbitMqConstantConfig;

    @Resource
    private TicketDao ticketDao;

    @Resource
    private TicketRecordDao ticketRecordDao;

    private XmMessageProducer messageProducer;

    @Autowired
    public void setMessageProducer(XmMessageProducer messageProducer) {
        this.messageProducer = messageProducer;
    }

    /**
     * 联系人3.0 p2修改，兼容手动创建工单时关联多个联系人情况
     *
     * @param ticket
     */
    @Override
    public void publishMemberFootSaveMqRefactor(Ticket ticket) {
        // 查询最新的ticket 保证ticket的更新时间最新
        Ticket nowTicket = ticketDao.findById(ticket.getId());
        String memberId = nowTicket.getMemberId();
        if (StringUtils.isNotBlank(memberId)) {
            String[] split = memberId.split(",");
            for (String s : split) {
                if (ObjectId.isValid(s)) {
                    ticket.setMemberId(s);
                    this.publishMemberFootSaveMq(nowTicket);
                }
            }
        }
    }

    private void publishMemberFootSaveMq(Ticket ticket) {
        if (Validator.isEmpty(ticket.getMemberId())) {
            log.info("[Ticket] 工单同步到足迹点,没有发现memberid");
            return;
        }
        Map<String, Object> mqMsg = getMemberFootSaveMsg(ticket);
//        try {
////            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppBpDirectExchange(),
////                    rabbitMqConstantConfig.getAppBpRoutingKey(), MEMBER_FOOTPRINT_SAVE, mqMsg);
//            FootprintMessage footprintMessage = MsgPackFormatUtil.mapToObj(mqMsg, FootprintMessage.class);
//            memberMessageService.footprintSaveSend(footprintMessage);
//            if (log.isInfoEnabled()) {
//                log.info("[Ticket] 发送mq消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppBpDirectExchange(),
//                        rabbitMqConstantConfig.getAppBpRoutingKey(), MEMBER_FOOTPRINT_SAVE, mqMsg);
//            }
//        } catch (Exception e) {
//            log.error("[Ticket] 发送mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppBpDirectExchange(),
//                    rabbitMqConstantConfig.getAppBpRoutingKey(), MEMBER_FOOTPRINT_SAVE, mqMsg);
//        }
        FootprintMessage footprintMessage = null;
        try {
            footprintMessage = MsgPackFormatUtil.mapToObj(mqMsg, FootprintMessage.class);
        } catch (IOException ignored) {
        }
        this.footprintSaveSend(footprintMessage);
    }

    private Map<String, Object> getMemberFootSaveMsg(Ticket ticket) {
        HashMap<String, Object> content = new HashMap<>();
        TicketConfig ticketConfig = ticketConfigDao.findById(ticket.getTicketConfigId());
        TicketRecord lastOneByTicketId = ticketRecordDao.findLastOneByTicketId(ticket.getId());
        String title;
        if (TicketOperationTypeEnum.MANUAL.getIndex().equals(ticket.getOperationType())) {
            title = ticket.getName();
        } else {
            title = ticketConfig.getTitle();
        }
        content.put("title", title);
        content.put("project_name", ticket.getSurveyTitle());
        content.put("ticket_status", ticket.getStatus());
        if (Objects.nonNull(lastOneByTicketId)) {
            String ticketUpdateTimeStr = DateUtil.format(lastOneByTicketId.getCreatedDate(), DatePattern.NORM_DATETIME_PATTERN);
            content.put("update_ticket_status_time", Validator.isNotEmpty(ticketUpdateTimeStr) ? ticketUpdateTimeStr : "");
        } else {
            String ticketUpdateTimeStr1 = DateUtil.format(ticket.getUpdatedDate(), DatePattern.NORM_DATETIME_PATTERN);
            content.put("update_ticket_status_time", Validator.isNotEmpty(ticketUpdateTimeStr1) ? ticketUpdateTimeStr1 : "");
        }
        HashMap<String, Object> memberFootprintData = new HashMap<>();
        memberFootprintData.put("org_id", ticket.getOrgId());
        memberFootprintData.put("member_id", ticket.getMemberId());
        memberFootprintData.put("type", MemberFootprintTypeEnum.TICKET.getIndex());
        memberFootprintData.put("source_key", ticket.getId());
        memberFootprintData.put("content", content);
        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_PATTERN);
        memberFootprintData.put("footprint_time", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
        return memberFootprintData;
    }

    /**
     * 发送工单变化的mq
     *
     * @param ticket 工单信息
     * @author jy.zhao
     * @date 2021/8/24 13:09
     **/
    @Override
    public void publishTicketChangeMq(Ticket ticket) {
        Map<String, Object> mqMsg = getTicketChangeMsg(ticket);
//        try {
//            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_CHANGED, mqMsg);
//            if (log.isInfoEnabled()) {
//                log.info("[Ticket] 发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                        ROUTING_KEY, TICKET_CHANGED, mqMsg);
//            }
//        } catch (JsonProcessingException e) {
//            log.error("[Ticket] 发送工单状态mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                    ROUTING_KEY, TICKET_CHANGED, mqMsg);
//        }
        this.ticketChangedFanoutSend(mqMsg);

    }


    /**
     * 发送工单的mq
     *
     * @param ticket    工单信息
     * @param groupInfo 组织信息
     * @author jy.zhao
     * @date 2021/8/24 13:09
     **/
    @Override
    public void publishTicketCreateMQ(Ticket ticket, Map<String, String> groupInfo) {
        Map<String, Object> mqMsg = getTicketCreateMsg(ticket, groupInfo);
//        try {
//            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_CREATED, mqMsg);
//            if (log.isInfoEnabled()) {
//                log.info("[Ticket] 创建工单发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                        ROUTING_KEY, TICKET_CREATED, mqMsg);
//            }
//        } catch (JsonProcessingException e) {
//            log.error("[Ticket] 创建工单发送mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                    ROUTING_KEY, TICKET_CREATED, mqMsg);
//        }
        this.ticketCreatedFanoutSend(mqMsg);
    }

    @Override
    public void publishTicketRecordCreateMq(Ticket ticket, TicketRecord ticketRecord, String userGroupCode, String surveyNo, String regionName) {
        Map<String, Object> mqMsg = getTicketRecordCreateMsg(ticket, ticketRecord, userGroupCode, surveyNo, regionName);
//        try {
//            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
//            if (log.isInfoEnabled()) {
//                log.info("[Ticket] 发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                        ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
//            }
//        } catch (JsonProcessingException e) {
//            log.error("[Ticket] 发送工单记录mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                    ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
//        }
        this.ticketRecordCreatedSend(mqMsg);

    }

    /**
     * 记录工单的各个进度.mq发送
     *
     * @param ticketRecord 工单记录
     * @author jy.zhao
     * @date 2021/8/24 14:09
     **/
    @Override
    public void publishTicketRecordCreateMq(Ticket ticket, TicketRecord ticketRecord) {
        Map<String, Object> mqMsg = getTicketRecordCreateMsg(ticket, ticketRecord);
//        try {
//            rabbitMessageSender.sendMsg(rabbitMqConstantConfig.getAppFanoutExchange(), ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
//            if (log.isInfoEnabled()) {
//                log.info("[Ticket] 发送目前消息成功, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                        ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
//            }
//        } catch (JsonProcessingException e) {
//            log.error("[Ticket] 工单记录创建发送mq消息失败, EXCHANGE_NAME={}, ROUTING_KEY={}, topic={}, mqMsg={}", rabbitMqConstantConfig.getAppFanoutExchange(),
//                    ROUTING_KEY, TICKET_RECORD_CREATED, mqMsg);
//        }
        this.ticketRecordCreatedSend(mqMsg);
    }

    /**
     * 计算周期行任务通知 发送提醒消息 延时MQ
     */
    private void ticketSendNotifySend(TicketSendDTO ticketSendDTOFreq, Date sendMqDelayDate) throws JsonProcessingException {
        messageProducer.sendDelay(StreamMqBinderConstants.TICKET_SEND_NOTIFY_OUT, ticketSendDTOFreq, sendMqDelayDate);
    }

    /**
     * 计算周期行任务通知 发送提醒消息 延时MQ
     */
    @Override
    public void ticketSendNotifySend(TicketSendDTO ticketSendDTOFreq, Date sendMqDelayDate, String msg) {
        if (log.isInfoEnabled()) {
            log.info("[Ticket] 计算周期行任务通知 {} 发送提醒消息延时MQ; {},{}", msg, JSONUtil.toJsonStr(ticketSendDTOFreq), sendMqDelayDate);
        }
        try {
            this.ticketSendNotifySend(ticketSendDTOFreq, sendMqDelayDate);
        } catch (JsonProcessingException e) {
            log.error(" [Ticket] 计算周期行任务通知 {} 发送提醒消息失败:{}", msg, JSONUtil.toJsonStr(ticketSendDTOFreq), e);
        }
    }

    /**
     * 工单流转 发送提醒消息 延时MQ
     */
    private void ticketOverDueSend(FollowOverdueDTO followOverdueDTO, Date sendTime) throws JsonProcessingException {
        messageProducer.sendDelay(StreamMqBinderConstants.TICKET_TICKET_OVERDUE_OUT, followOverdueDTO, sendTime);
    }

    /**
     * 工单流转 发送提醒消息 延时MQ
     */
    @Override
    public void ticketOverDueSend(FollowOverdueDTO followOverdueDTO, Date sendTime, String msg) {
        if (log.isInfoEnabled()) {
            log.info("[Ticket] 工单流转 {} 发送提醒消息延时MQ; {},{}", msg, JSONUtil.toJsonStr(followOverdueDTO), sendTime);
        }
        try {
            this.ticketOverDueSend(followOverdueDTO, sendTime);
        } catch (JsonProcessingException e) {
            log.error(" [Ticket] 算周期行任务通知 {}发送提醒消息失败:{}", msg, JSONUtil.toJsonStr(followOverdueDTO), e);

        }
    }

    /**
     * 发送工单创建MQ-fanout
     */
    @Override
    public void ticketRecordCreatedSend(Object data) {
        if (log.isInfoEnabled()) {
            log.info("[Ticket] 发送工单创建MQ {} ", JSONUtil.toJsonStr(data));
        }
        try {
            messageProducer.send(StreamMqBinderConstants.TICKET_RECORD_CREATED_OUT, data);
        } catch (JsonProcessingException e) {
            log.error("[Ticket] 发送工单创建MQ失败 {} ", JSONUtil.toJsonStr(data), e);
        }
    }

    /**
     * 工单预警触发队列消息
     */
    @Override
    public void ticketRuleTriggeredSend(RspdTimerDTO rspdTimerDTO) {
        if (log.isInfoEnabled()) {
            log.info("[Ticket] 工单预警触发队列消息 {} ", JSONUtil.toJsonStr(rspdTimerDTO));
        }
        try {
            messageProducer.send(StreamMqBinderConstants.TICKET_RULE_TRIGGERED_OUT, rspdTimerDTO);
        } catch (JsonProcessingException e) {
            log.error("[Ticket] 工单预警触发队列消息失败 {} ", JSONUtil.toJsonStr(rspdTimerDTO), e);
        }
    }

    /**
     * 工单创建-fanout
     */
    private void ticketCreatedFanoutSend(Map<String, Object> mqMsg) {
        if (log.isInfoEnabled()) {
            log.info("[Ticket] 工单创建-fanout {} ", JSONUtil.toJsonStr(mqMsg));
        }
        try {
            messageProducer.send(StreamMqBinderConstants.TICKET_CREATED_FANOUT_OUT, mqMsg);
        } catch (JsonProcessingException e) {
            log.error("[Ticket] 工单创建-fanout失败 {} ", JSONUtil.toJsonStr(mqMsg), e);
        }
    }

    /**
     * 工单变化-fanout
     */
    private void ticketChangedFanoutSend(Map<String, Object> mqMsg) {
        if (log.isInfoEnabled()) {
            log.info("[Ticket] 工单变化-fanout {} ", JSONUtil.toJsonStr(mqMsg));
        }
        try {
            messageProducer.send(StreamMqBinderConstants.TICKET_CHANGED_FANOUT_OUT, mqMsg);
        } catch (JsonProcessingException e) {
            log.error("[Ticket] 工单变化-fanout失败 {} ", JSONUtil.toJsonStr(mqMsg), e);
        }
    }

    /**
     * 存联系人足迹
     */
    private void footprintSaveSend(FootprintMessage message) {
        try {
            messageProducer.send(StreamMqBinderConstants.MEMBER_FOOT_PRINT_SAVE_OUT, message);
        } catch (JsonProcessingException e) {
            log.error("[Ticket] footprintSaveSend失败 {} ", JSONUtil.toJsonStr(message), e);
        }
    }

    /**
     * 工单记录创建mq信息
     *
     * @param ticket       工单信息
     * @param ticketRecord 工单记录信息
     * @return Map<String, Object>
     * @author jy.zhao
     * @date 2021/9/2 23:30
     **/
    private Map<String, Object> getTicketRecordCreateMsg(Ticket ticket, TicketRecord ticketRecord) {
        String userGroupCode = "";
        if (Validator.isNotEmpty(ticket.getRegion())) {
            GroupDTO groupDTO = ticketBaseUserGrpcService.getGroup(ticket.getRegion());
            if (Validator.isNotNull(groupDTO)) {
                userGroupCode = groupDTO.getCode();
            }
        }
        String surveyNo = "";
        if (Validator.isNotEmpty(ticket.getSurveyId())) {
            // 根据问卷id查询问卷项目，得到问卷编号
            QdesDTO surveyProject = ticketBaseQdesGrpcService.getQdesProject(ticket.getSurveyId());
            if (Validator.isNotNull(surveyProject)) {
                surveyNo = surveyProject.getCode();
            }
        }
        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
        // 问卷id
        mqMsg.put("surveyId", ticket.getSurveyId());
        // 工单号
        mqMsg.put("ticketNo", ticket.getTicketNo());
        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
        // 工单创建时间
        mqMsg.put("ticket_created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
        // 工单状态
        mqMsg.put("status", ticket.getStatus());
        // 层级id
        mqMsg.put("region", ticket.getRegion());
        //
        mqMsg.put("code", userGroupCode);

        // 层级名称
        mqMsg.put("regionName", ticket.getRegionName());
        // 问卷标题
        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
        // 问卷编号
        mqMsg.put("surveyNo", surveyNo);
        //
        mqMsg.put("resId", ticket.getResId());
        // 工单id
        mqMsg.put("ticketId", ticket.getId());
        // 工单事件
        mqMsg.put("event", ticketRecord.getEvent());
        // 工单title
        mqMsg.put("title", ticketRecord.getTitle());
        // 用户id
        mqMsg.put("userId", "");
        // 用户名称
        mqMsg.put("userName", ticketRecord.getUserName());
        // 手动还是自动
        mqMsg.put("source", ticketRecord.getSource());
        // 角色id
        mqMsg.put("roleId", Validator.isNotNull(ticketRecord.getRoleId()) ? ticketRecord.getRoleId() : "");
        // ticketRecordId，日志记录id
        mqMsg.put("id", ticketRecord.getId());
        String ticketRecordCreateTimeStr = DateUtil.format(ticketRecord.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
        // 日志创建时间
        mqMsg.put("created_dt", Validator.isNotEmpty(ticketRecordCreateTimeStr) ? ticketRecordCreateTimeStr : "");
        return mqMsg;
    }


    private Map<String, Object> getTicketRecordCreateMsg(Ticket ticket, TicketRecord ticketRecord, String userGroupCode, String surveyNo, String regionName) {

        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
        // 问卷id
        mqMsg.put("surveyId", ticket.getSurveyId());
        // 工单号
        mqMsg.put("ticketNo", ticket.getTicketNo());
        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
        // 工单创建时间
        mqMsg.put("ticket_created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
        // 工单状态
        mqMsg.put("status", ticketRecord.getTicketStatus());
        // 层级id
        mqMsg.put("region", ticket.getRegion());
        //
        mqMsg.put("code", userGroupCode);

        // 层级名称
        mqMsg.put("regionName", regionName);
        // 问卷标题
        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
        // 问卷编号
        mqMsg.put("surveyNo", surveyNo);
        //
        mqMsg.put("resId", ticket.getResId());
        // 工单id
        mqMsg.put("ticketId", ticket.getId());
        // 工单事件
        mqMsg.put("event", ticketRecord.getEvent());
        // 工单title
        mqMsg.put("title", ticketRecord.getTitle());
        // 用户id
        mqMsg.put("userId", "");
        // 用户名称
        mqMsg.put("userName", ticketRecord.getUserName());
        // 手动还是自动
        mqMsg.put("source", ticketRecord.getSource());
        // 角色id
        mqMsg.put("roleId", Validator.isNotNull(ticketRecord.getRoleId()) ? ticketRecord.getRoleId() : "");
        // ticketRecordId，日志记录id
        mqMsg.put("id", ticketRecord.getId());
        String ticketRecordCreateTimeStr = DateUtil.format(ticketRecord.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
        // 日志创建时间
        mqMsg.put("created_dt", Validator.isNotEmpty(ticketRecordCreateTimeStr) ? ticketRecordCreateTimeStr : "");
        return mqMsg;
    }

    /**
     * 获取工单创建、修改消息数据
     *
     * @param ticket 工单信息
     * @return Map<String, Object>
     * @author jy.zhao
     * @date 2021/8/26 17:28
     **/
    private Map<String, Object> getTicketCreateMsg(Ticket ticket, Map<String, String> groupInfo) {
        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
        mqMsg.put("surveyId", ticket.getSurveyId());
        mqMsg.put("ticketNo", ticket.getTicketNo());
        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
        mqMsg.put("created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
        mqMsg.put("status", ticket.getStatus());
        mqMsg.put("region", ticket.getRegion());
        mqMsg.put("code", groupInfo.getOrDefault("userGroupCode", Constants.BLANK));
        mqMsg.put("regionName", ticket.getRegionName());
        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
        mqMsg.put("surveyNo", groupInfo.getOrDefault("surveyCode", Constants.BLANK));
        mqMsg.put("resId", ticket.getResId());
        mqMsg.put("id", ticket.getId());
        mqMsg.put("followRoleId", ticket.getFollowRoleId());
        mqMsg.put("auditRoleId", ticket.getAuditRoleId());

        if (Validator.isNotEmpty(ticket.getRegion())) {
            List<GroupNodeDTO> groupNodeDTOList = ticketUserGrpcService.listAncestorGroupsByGroupId(ticket.getRegion());
            if (CollUtil.isNotEmpty(groupNodeDTOList)) {
                for (GroupNodeDTO node : groupNodeDTOList) {
                    mqMsg.put(node.getId(), Optional.ofNullable(node.getTitle()).orElse(Constants.BLANK));
                }
            }
        }
        return mqMsg;
    }

    /**
     * 获取工单创建、修改消息数据
     *
     * @param ticket 工单信息
     * @return Map<String, Object>
     * @author jy.zhao
     * @date 2021/8/26 17:28
     **/
    private Map<String, Object> getTicketChangeMsg(Ticket ticket) {
        String userGroupCode = "";
        if (Validator.isNotEmpty(ticket.getRegion())) {
            GroupDTO groupDTO = ticketBaseUserGrpcService.getGroup(ticket.getRegion());
            if (Validator.isNotNull(groupDTO)) {
                userGroupCode = groupDTO.getCode();
            }
        }
        String surveyNo = "";
        if (Validator.isNotEmpty(ticket.getSurveyId())) {
            // 根据问卷id查询问卷项目，得到问卷编号
            QdesDTO qdesProject = ticketBaseQdesGrpcService.getQdesProject(ticket.getSurveyId());
            if (Validator.isNotNull(qdesProject)) {
                surveyNo = qdesProject.getCode();
            }
        }
        Map<String, Object> mqMsg = new HashMap<>(Constants.DEFAULT_MAP_INITIAL_CAPACITY);
        mqMsg.put("surveyId", ticket.getSurveyId());
        mqMsg.put("ticketNo", ticket.getTicketNo());
        String ticketCreateTimeStr = DateUtil.format(ticket.getCreatedDate(), DatePattern.NORM_DATETIME_MS_PATTERN);
        mqMsg.put("created_dt", Validator.isNotEmpty(ticketCreateTimeStr) ? ticketCreateTimeStr : "");
        mqMsg.put("status", ticket.getStatus());
        mqMsg.put("region", ticket.getRegion());
        mqMsg.put("code", userGroupCode);
        mqMsg.put("regionName", ticket.getRegionName());
        mqMsg.put("surveyTitle", ticket.getSurveyTitle());
        mqMsg.put("surveyNo", surveyNo);
        mqMsg.put("resId", ticket.getResId());
        mqMsg.put("id", ticket.getId());
        mqMsg.put("followRoleId", ticket.getFollowRoleId());
        mqMsg.put("auditRoleId", ticket.getAuditRoleId());

        if (Validator.isNotEmpty(ticket.getRegion())) {
            List<GroupNodeDTO> groupNodeDTOList = ticketUserGrpcService.listAncestorGroupsByGroupId(ticket.getRegion());
            if (CollUtil.isNotEmpty(groupNodeDTOList)) {
                for (GroupNodeDTO node : groupNodeDTOList) {
                    mqMsg.put(node.getId(), Optional.ofNullable(node.getTitle()).orElse(Constants.BLANK));
                }
            }
        }
        return mqMsg;
    }
}
